<?php

class  ApiCenter_ProductApi_Model_Api2_Product_Save  extends  Mage_Api2_Model_Resource {
    const ATTRIBUTE_CODE = 'media_gallery';

    const DEFULT_VISIBILITY = "1";
     
    const DEFULT_STAUTS = "2";
     
    const DEFULT_APPROVAL = "0";

    const  WEBSITEID = "1";

    protected  $need_filter = array(
        "name",
        "description",
        "short_description",
    );
    private $imageMap = array(
        'label'    => 'label',
        'file' => 'file',
    );
    private   $step_1 =array(
        "General"
    );
    private   $step_2 =array(
        "Basic Product Information",
        "Prices",
    );
    private   $step_3 =array(
        "Additional Product Information",
    );
    private $filterArr = array(
       "pulscen",
        "giftcard_amounts",
       "allow_open_amount",
       "common_weight",
       "open_amount_min",
       "open_amount_max",
       "group_price",
       "tier_price",
       "common_supply_price",
       "msrp_enabled",
       "msrp_display_actual_price_type",
       "common_supplier_special_price",
         "attr_giftcard_amounts",
        "fb_product",
       "news_from_date",
       "news_to_date",
       "url_key",
       "country_of_manufacture",
       "is_returnable",
       "em_featured",
       "em_deal",
       "em_hot",
       "yml",
        "sku",
       "vendor_id",
        "visibility",
       "status",
        "approval",
       "yandex_market_product_category",
       "tax_class_id",
       "tiers_table",
       "msrp",
        "cost",
       "common_other_shipping_type",
       "common_publish_platform",
       "common_shipping_method",
       "common_dimensional_weight",
       "inventory_manage_stock",
       "inventory_min_sale_qty",
       "inventory_max_sale_qty",
       "inventory_is_qty_decimal",
       "inventory_notify_stock_qty",
       "inventory_enable_qty_increments",
       "inventory_backorders",
       "simple_product_visibility",
    );
  
    public  $childAttr =array(
        "weight",
        "vendor_sku",
    );
    public  $stock_qty=array(
        "attribute_code" => "qty",
        "frontend_label" => "库存",
        "is_required"  =>"1",
        "frontend_input"=>"text"
    );

    public  $media_gallery = array(
        "attribute_code" => "media_gallery",
        "frontend_label" => "商品图片",
        "is_required"  =>"0",
        "frontend_input"=>"text"
    );

    private $readonly = array(
        "common_reasons",
    );
    private  $hidden = array(
         
    );
    private $websiteIds = array(
        "1"
    );
    
    /**
     * 加载子产品
     * */
    protected function _loadchildproduct($product,$childOption){
        $products = $product->getTypeInstance(true)
        ->getUsedProducts(null, $product);
        foreach($products as $_product){
            $data[$_product->getId()] = $this->getConfigurableSettings($_product,$product);
            $this->stock_qty['product_value'] = $_product->getStockItem()->getQty();
            $data[$_product->getId()][] =$this->stock_qty;
            $this->vendor_sku["product_value"] = $_product->getVendorSku();
            $data[$_product->getId()][] =$this->vendor_sku;
        }
        return $data;
    }
    /**
     * 获取可配置产品的超级属性
     * */
    protected function getConfigurableSettings($product,$main_product) {

        $childOption = Mage::registry("super_option")?Mage::registry("super_option"):array();
        $data = array();
        $attributes = $main_product->getTypeInstance(true)
        ->getUsedProductAttributes($main_product);
        foreach ($attributes as $attribute) {
            $data[] = array(
                'attribute_id' => $attribute->getId(),
                'attribute_code' => $attribute->getAttributeCode(),
                'label'        => $product->getAttributeText($attribute->getAttributeCode()),
                'product_value'  => $product->getData($attribute->getAttributeCode()),
                'frontend_input' => $attribute->getFrontendInput(),
                "select_option" =>$childOption[$attribute->getAttributeCode()]
            );
        }
        return $data;
    }
    
    
    /**
     *  加载category的所有父集category
     * */
    
    protected  function _loadAllParentCategory($categoryid,&$ids){
        
        $_categoryData = Mage::getModel('catalog/category')->load($categoryid)->getData();
        	
        $val['name'] = $_categoryData['name'];
        $val['url_key'] = $_categoryData['url_key'];
        $ids[$_categoryData['entity_id']] = $val;
        if($_categoryData['parent_id'] !="2"){
            $this->_loadAllParentCategory($_categoryData['parent_id'],$ids);
        }
    }
    
    /**
     *
     * 加载set_id的属性集 并添加某个属性的值
     * */
    protected function _loadRequireField($set_id,$type){
        $collection = Mage::getResourceModel('catalog/product_attribute_collection')
        ->setAttributeSetFilter($set_id)
        ->addVisibleFilter()
        ->load();

        $attr = $collection->getData();

        /* @var $helper ApiCenter_ProductApi_Helper_Data */
        $helper = Mage::helper("productapi");
    
        $check_filter=array();
        $childOption = array();
        foreach ($attr as $i=>$val){
            $group_name = $helper->getAttributeGroupAction($val['attribute_group_id']);

            if (in_array($val['attribute_code'], $this->filterArr)) continue;
            if(in_array($val['attribute_code'], $this->readonly)) $val["read_only"]=1;
    
            if($type == 'configurable' &&in_array($val['attribute_code'],$this->childAttr)||$val['is_global'] == '1' && $val['frontend_input'] == 'select' && $val['is_configurable']="1"){
                
                continue;
            }
            $check_filter[]=$val;
        }
            if($type=="simple"){
                $check_filter[]=$this->stock_qty;
            }       
            $check_filter[]=$this->media_gallery;
            return $check_filter;

    }

    protected  function validateChildProduct($childProduct,$super_attr){
        $child_filter = array_merge($super_attr,$this->childAttr);
        foreach ($child_filter as $v){
            $isRequire =Mage::getSingleton("catalog/product")->getResource()->getAttribute($v)->getIsRequired();
            foreach ($childProduct as $product){
                if($isRequire=="1"&&!isset($product[$v])){
                    $this->_critical("please set".$v,400);
                }
            }
        }
    }
    /**
     *  对商品数据进行预处理
     *
     *  @param    Mage_Catalog_Model_Product $product
     *  @param    array $productData
     *  @return   object
     */
    protected function _prepareDataForSave($product, $productData,$type)
    {
       
       $edit =  $this->getRequest()->getParam("id",null);
        /*@var $helper ApiCenter_ProductApi_Helper_Data*/
        $helper = Mage::helper("productapi");
        //将所有的值首先set
        foreach ($productData as $k =>$v){
            if(isset($productData[$k])){
                if($k == 'special_from_date'&&$v==""){
                    $v=false;
                }
                $product->setData(
                   $k, $v
                );
            }
        }
        
        //获取商家id
        $vendorId  = $this->getRequest()->getParam("vendorid");
        
        //默认税为空
        $product->setTaxClassId(0);
        
        //设置默认状态 禁用
        if($product->getStatus()==1&&$product->getId()){
            $product->setStatus(1);
        }else{
            $product->setStatus(self::DEFULT_STAUTS);
        } 
        //设置为未审核
        
        if($product->getApproval()==2&&$edit){
            $product->setApproval(2);
        }else{
            $product->setApproval(self::DEFULT_APPROVAL);
        }
      

        //设置默认商家Id
        $product->setVendorId($vendorId);
         
        
        //处理图片编辑器的数据
        if(isset($productData['description'])){
            $description = $helper->togetherMageImage($productData['description']);
            $product->setDescription($description);
        }
        
        
        if(isset($productData['short_description'])){
            $shortdescription = $helper->togetherMageImage($productData['short_description']);
            $product->setShortDescription($shortdescription);
        }
        
        //设置运费
//         $cost= $this->_calculatepPrice($productData,$vendorId);
//         $product->setCost($cost);

        //设置总价格
//         $price =$cost+$productData['common_supply_price'];
//         $product->setPrice($price);

//         //根据不同类型商品做处理
//         if($type=="simple"){
//             $product->setVisibility(self::DEFULT_VISIBILITY);
//         }
        
        if(isset($productData['qty'])){
            
            if($edit&&!empty($product->getId())){
                $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
                $stockItem->setData('qty',$productData['qty']);
                if($productData['qty']<1){
                    $stockItem->setData('is_in_stock',0);
                }else{
                    $stockItem->setData('is_in_stock',1);
                }
                $stockItem->save();
            }else{
                $_stockData = array(
                 //  'use_config_manage_stock' => 0,
                  'manage_stock' => 1, //manage stock
                    'qty' =>$productData['qty'],
                     'is_in_stock'=>!empty($productData['qty'])?1:0,
                     'is_decimal_divided' => 0,     
                    'use_config_min_qty'=>1,
                    'use_config_backorders'=>1,
                     'use_config_min_sale_qty'=>1,
                     'use_config_max_sale_qty'=>1,
                     'use_config_notify_stock_qty'=>1,
                   'use_config_enable_qty_increments'=>1,
                );
                $product->setStockData($_stockData);
            }
        }else{
            //新增
            if(empty($product->getId())){
                $_stockData = array(
                    'manage_stock' => 0, //manage stock
                    'use_config_manage_stock' => 0,
                );
                $product->setStockData($_stockData);
            }else{
                
            }
         
        }
     
        //处理图片
        $image_gallery =array(
            "images"=>array(),
        );
        if(isset($productData['images']) && is_array($productData['images'])){
                $tmp_image =$productData['images'];
                
                foreach($tmp_image as $k => $_image){
                    if(!empty($_image['value_id'])){
                        $image_data['value_id'] =$_image['value_id'];
                    }else{
                        unset($image_data['value_id']);
                    }
                    if(isset($_image['value_id'])){
                        $image_data['product_id'] =$product->getId();
                    }
                    $image_data['label'] =$_image['label'];
                    $image_data['file'] =$_image['file'];
                    $image_data['position'] =$_image['position'];
                    $image_data['disabled'] =0;
                    if(!empty($_image['removed'])){
                        $image_data['removed'] =1;
                    }else{
                        unset($image_data['removed']);
                    }
                    $image_gallery['images'][] =$image_data;
                    if($_image['is_main']==1){
                        $image_gallery['values']['image']=$_image['file'];
                        $product->setImage($_image['file']);
                    }
                    if($_image['is_thumbnail']==1){
                        $image_gallery['values']['thumbnail']=$_image['file'];
                        $product->setThumbnail($_image['file']);
                    }
                    if($_image['is_smallimage']==1){
                          $image_gallery['values']['small_image']=$_image['file'];
                          $product->setSmallImage($_image['file']);
                    }
                }
                if(!empty( $image_gallery['images'])){
                    $product->setMediaGallery($image_gallery);
                }
        }
        if (isset($productData['website_ids']) && is_array($productData['website_ids'])) {
            $product->setWebsiteIds($productData['website_ids']);
        }
         
         
        if (isset($productData['categories']) && is_array($productData['categories'])) {
            $allCategoryInfo = array();
            $MetaKeyword ="";
            
            if(count($productData['categories']) == 1 ){
              $category_id = $productData['categories'][0];
            }else{
                $category_id =  max($productData['categories']);
            }
            //加载出所有父集category 返回 name url_key  
            $this->_loadAllParentCategory($category_id,$allCategoryInfo);
            ksort($allCategoryInfo);
            foreach ($allCategoryInfo as $cid =>$val){
                $productData['categories'][] =$cid;
                $MetaKeyword.=$val['name'].",";
            }
            $productData['categories']= array_unique($productData['categories']);
            
            $product->setMetaTitle("");
            $product->setMetaKeyword($MetaKeyword);
            $product->setMetaDescription("");
            $product->setCategoryIds($productData['categories']);
            
        }
         
        $productData['websites']=$this->websiteIds;
        if (isset($productData['websites']) && is_array($productData['websites'])) {
            foreach ($productData['websites'] as &$website) {
                if (is_string($website)) {
                    try {
                        $website = Mage::app()->getWebsite($website)->getId();
                    } catch (Exception $e) { }
                }
            }
            $product->setWebsiteIds($productData['websites']);
        }
         
        if (Mage::app()->isSingleStoreMode()) {
            $product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
        }
              
        if (isset($productData['tier_price']) && is_array($productData['tier_price'])) {
            $tierPrices = Mage::getModel('catalog/product_attribute_tierprice_api')
            ->prepareTierPrices($product, $productData['tier_price']);
            $product->setData(Mage_Catalog_Model_Product_Attribute_Tierprice_Api::ATTRIBUTE_CODE, $tierPrices);
        }
        //可配置商品需要传输的参数
        if ($type=='configurable'&& is_array($productData['configurable_attributes_data'])) {
            $product->setConfigurableAttributesData($productData['configurable_attributes_data']);
        }
         
        if ($type=='configurable'&& is_array($productData['configurable_products_data'])) {
            $product->setConfigurableProductsData($productData['configurable_products_data']);
        }
         
        if ($type=='configurable'&& $productData['can_save_configurable_attributes']) {
            $product->setCanSaveConfigurableAttributes(true);
        }
    }

    /**
     * 验证数据
     *
     * */
    protected  function  validateProduct($productData,$type,$set){
        $error = "";
        //获取相关需要填写的属性
         $required_fields = $this->_loadRequireField($set,$type);

        foreach ($required_fields as $key => $attribute){
                if($attribute['is_required']==1){
                    if(!isset($productData[$attribute['attribute_code']])){
                        $error.=$attribute['attribute_code']."字段为必填字段|";
                    }
                }
        }
        
//         $pattern = '/([/x80-/xff])/';
//         foreach ($this->need_filter as $v){
//             if($productData[$v]){
//                 if(preg_match($pattern,$productData[$v])){
//                     $error.=$v."字段含有中文|";
//                 }
//             }
//         }

        Mage::log($error);
        if(!empty($error)){
            $this->_critical($error,400);
        }
    }
    /**
     * 检查属性集是否存在
     *
     * @param  $attributeSetId
     * @throw Mage_Api_Exception
     * @return void
     */
    protected function _checkProductAttributeSet($attributeSetId)
    {
        $attributeSet = Mage::getModel('eav/entity_attribute_set')->load($attributeSetId);
        if (is_null($attributeSet->getId())) {
            $this->_critical('产品属性集不存在',400);
        }
        if (Mage::getModel('catalog/product')->getResource()->getTypeId() != $attributeSet->getEntityTypeId()) {
            $this->_critical('产品属性集不存在',400);
        }
    }
    /**
     * 计算运费价格
     * */
    protected  function _calculatepPrice($productData,$vendorid){
        //获取长宽高、物流方式、是否轻抛
        $dataPrice['length'] = $productData['common_package_length'];
        $dataPrice['width'] = $productData['common_package_width'];
        $dataPrice['height'] = $productData['common_package_height'];
        $dataPrice['shipping_type'] = $productData['common_shipping_type'];
        $dataPrice['weight'] =$productData['weight'];
        $dataPrice['dimensional_weight'] = $productData['common_dimensional_weight'];
         
        foreach ($dataPrice as $v){
            if(is_null($v)){
                $this->_critical("calculate_field_is_null");
            }
        }
        if($dataPrice['shipping_type']=="14"&&$dataPrice['dimensional_weight']=="1"){
            $finall_weight = ($dataPrice['length']*$dataPrice['width']*$dataPrice['height'])/12000;
        }else{
            $finall_weight =  $dataPrice['weight'];
        }
        //请求运费价格接口算出运费
        $cost = Mage::helper("shippingquery") -> returnShippingPrice($vendorid,$dataPrice['shipping_type'],$finall_weight);
        if($cost){
            return $cost;
        }else{
            $this->_fault("To_calculate_failure");
        }
    }
    /**
     * 检测商品类型是否存在
     *
     * */
    protected function _checkProductTypeExists($productType)
    {
        if (!in_array($productType, array_keys(Mage::getModel('catalog/product_type')->getOptionArray()))) {
            $this->_critical('产品类型不存在',400);
        }
    }
    /**
     * 检测组合产品的sku是否已经存在或重复
     * */
    protected  function _checkSkuExists($Skus,$vendor_id){
        $error ="";
        foreach ($Skus as $_sku){
            $sku = $vendor_id."_".$_sku;
            $id = Mage::getModel('catalog/product')->getIdBySku($sku);
            if ($id) {
                $error.=$sku.",";
            }
        }
      if(!empty($error)){
          $this->_critical($error."sku已存在",400);
      }
      // 获取去掉重复数据的数组
      $unique_skus = array_unique ( $Skus );
      // 获取重复数据的数组
      $repeat_arr = array_diff_assoc ( $Skus, $unique_skus );
      if(!empty($repeat_arr)){
         $error = implode(",", $repeat_arr);
          $this->_critical($error."sku内部重复",400);
      }
    }
}